﻿Imports System.Data.SqlClient
Imports System.Data
Imports System.Data.OleDb
Imports System.Net
Imports System.Net.Sockets
Imports System.IO

Public Class Form1
    Dim orderfrm As New orders
    Public MainForm As mainform

#Region "MAIN"
    Sub GetMySentData()
        Try
            ToolStripStatusLabel1.Text = "Checking for new orders.."
            Dim myConn As SqlConnection
            Dim myCmd As SqlCommand
            Dim myReader As SqlDataReader
            append("Connecting to Server..")
            myConn = New SqlConnection(MainForm.ConnectionString)
            ' MsgBox("SELECT * from [Management_Info_Sys].[dbo].[delivery_items] where status='OPEN' and timestamp between '" & Today.AddDays(-1) & "' and '" & Today.AddDays(1) & "'")
            append("Collecting New Data..")
            myCmd = myConn.CreateCommand
            myCmd.CommandText = MainForm.CallCenterGetItemsCommand
            'MsgBox(MainForm.CallCenterGetItemsCommand)
            myConn.Open()
            append("Reading..")
            myReader = myCmd.ExecuteReader()

            Do While myReader.Read()
                'CheckDuplicate Order by dKey
                Dim Duplicate As Boolean = False
                For Each order As orders In FlowLayoutPanel1.Controls
                    'MsgBox(order.dKey)
                    'MsgBox(myReader.GetValue(0).ToString)
                    If order.dKey = myReader.GetValue(0).ToString Then
                        If order.Status <> myReader.GetValue(11).ToString Then
                            Try
                                order.Dispose()
                            Catch ex As Exception
                            End Try
                        Else
                            Duplicate = True
                        End If
                        Exit For
                    End If
                Next
                'append("Checking Integrity..")
                If Duplicate = False Then
                    Dim Serial As String = myReader.GetValue(1).ToString
                    Dim dKey As String = myReader.GetValue(0).ToString
                    Dim Guestname As String = myReader.GetValue(4).ToString
                    Dim GuestAddress As String = myReader.GetValue(5).ToString
                    Dim ContactNo As String = myReader.GetValue(6).ToString
                    Dim order_ As String = myReader.GetValue(7).ToString
                    Dim totalBill As String = myReader.GetValue(8).ToString
                    Dim specialIns As String = myReader.GetValue(9).ToString
                    Dim ChangeFor As String = myReader.GetValue(10).ToString
                    Dim Status As String = myReader.GetValue(11).ToString
                    Dim DateSent As String = myReader.GetValue(12).ToString
                    Dim Sender As String = myReader.GetValue(15).ToString
                    Dim DateModified As String = myReader.GetValue(14).ToString


                    orderfrm = New orders
                    orderfrm.mainform = MainForm
                    orderfrm.dKey = dKey
                    orderfrm.Serial = Serial
                    orderfrm.Status = Status
                    orderfrm.Guestname = Guestname
                    orderfrm.GuestAddress = GuestAddress
                    orderfrm.ContactNo = ContactNo
                    orderfrm.order_ = order_
                    orderfrm.totalBill = totalBill
                    orderfrm.ChangeFor = ChangeFor
                    orderfrm.DateSent = DateSent
                    orderfrm.sender_ = Sender
                    orderfrm.specialIns = specialIns
                    orderfrm.Button1.Text = "Preview"
                    orderfrm.DateModified = DateModified

                    'append("New Order Recieved!")
                    Dim Invoker As New MethodInvoker(AddressOf AddControl)
                    Me.Invoke(Invoker)
                End If
            Loop
            myReader.Close()
            myConn.Close()
            append("Done checking orders! Connection Closed.")
            ToolStripStatusLabel1.Text = "Idle"
        Catch ex As Exception

        End Try

    End Sub
    Sub SendDelivery()
        WhileRunning(False)
        Try
            append("Securing Request..")
            Dim Serial As String = "Sample"

            Dim myQuery As String
            append("Building Query..")
            myQuery = "serial=" & Serial & "&storename=" & cmbStorename.SelectedValue & "&storeip=" & cmbstore.SelectedValue & _
                "&guestname=" & txtguestname.Text & "&guestaddress=" & txtaddress.Text & "&contactno=" & txtcontactno.Text & _
                "&order=" & txtorder.Text & "&totalbill=" & txttotalbill.Text & "&specialins=" & txtspecialins.Text & _
                "&changefor=" & txtchangefor.Text & "&datesent=" & Now.ToString & "&sender=" & MainForm.Sender

            'MsgBox(Host & ":" & port & "/" & Webpage & "?" & myQuery)
            append("Transfering Data..")

            Dim Webreq As HttpWebRequest = DirectCast(WebRequest.Create(MainForm.Host & ":" & MainForm.port & "/" & MainForm.Sendpage & "?" & myQuery), HttpWebRequest)
            Webreq.Method = "GET"
            Webreq.KeepAlive = False
            append("Waiting for reply..")
            Dim postresponse As HttpWebResponse
            postresponse = DirectCast(Webreq.GetResponse(), HttpWebResponse)
            append(postresponse.StatusCode)
            If postresponse.StatusCode = HttpStatusCode.OK Then
                append("***Transfering Delivery Success***")
                ResetControl()
            Else
                append("Transfering Delivery Failed")
                append("********************************")
                append(postresponse.StatusDescription)
            End If
        Catch ex As Exception
            append("Process Interupted because : " & ex.Message)
        End Try
        WhileRunning(True)

    End Sub
    Sub SendDeliverySQL()
        Try
            WhileRunning(False)
            'Remove '
            Try
                For Each textb As Control In GroupBox1.Controls
                    If textb.GetType() Is GetType(TextBox) Then
                        textb.Text = textb.Text.Replace("'", "%27")
                    End If
                Next
            Catch ex As Exception
                'MsgBox(ex.Message)
            End Try

            Dim Last5Digit As Integer
            Dim rand5dig As New Random
            Last5Digit = rand5dig.Next(1000, 9999)

            'Ping
            'Check Store Delivery Relay


            Dim Serial As String = Now.Year & Now.Month & Now.Day & Last5Digit.ToString

            Dim myConn As SqlConnection
            Dim myCmd As SqlCommand
            myConn = New SqlConnection(MainForm.ConnectionString)
            myCmd = myConn.CreateCommand
            myCmd.CommandText = "INSERT INTO " & MainForm.DBTable & " VALUES ('" & _
            Serial & "','" & cmbStorename.Text & "','" & cmbstore.Text & "','" & _
            txtguestname.Text.ToUpper & "','" & txtaddress.Text.ToUpper & "','" & txtcontactno.Text.ToUpper & "','" & txtorder.Text.ToUpper & _
            "','" & txttotalbill.Text.ToUpper & "','" & txtspecialins.Text.ToUpper & "','" & txtchangefor.Text.ToUpper & "','OPEN','" & _
            Now.ToString.ToUpper & "','" & "','" & Now.ToString.ToUpper & "','" & My.Settings.MyNAme & "');"
            myConn.Open()
            myCmd.ExecuteNonQuery()

            append("***Order Added to Database***")
            If MainForm.UsePortToSendSignal = True Then
                If SendSignal(cmbstore.Text, Serial) Then
                    MsgBox("Order - " & Serial & " Sent.")
                End If
            End If
            WhileRunning(True)
        Catch ex As Exception
            append("Transfering Delivery Failed")
            append("********************************")
            append(ex.Message)
            MsgBox(ex.Message)
        End Try

        Try
            Dim t As New Threading.Thread(AddressOf GetMySentData)
            t.Start()
            ResetControl()
        Catch ex As Exception

        End Try
    End Sub
    Private Sub AddControl()
        FlowLayoutPanel1.Controls.Add(orderfrm)
    End Sub
    Public SenderClient As TcpClient
    Function SendSignal(IP As String, key As String) As Boolean
        Try
            SenderClient = New TcpClient(IP, MainForm.RealPort)
            Dim Writer As New StreamWriter(SenderClient.GetStream())
            'Writer.Write("</> " & "rar a C:\Users\sergentlois\Desktop\test.rar C:\zip" & " <\>")
            Writer.Write("</> " & key & " <\>")
            Writer.Flush()
            'Append True
            append("Order Recieved")
            Return True
        Catch ex As Exception
            'MsgBox(ex.Message)
            Return False
        End Try
    End Function
    Sub GetStores()
        Try
            ToolStripStatusLabel1.Text = "Initializing Stores.."
            Dim myConn As SqlConnection
            Dim myCmd As SqlCommand
            Dim myReader As SqlDataReader
            append("Connecting to Server..")
            myConn = New SqlConnection(MainForm.ConnectionString)
           
            append("Collecting..")
            myCmd = myConn.CreateCommand
            myCmd.CommandText = "SELECT  * from " & MainForm.Storestable & " where company='KR';"

            myConn.Open()
            append("Reading..")
            myReader = myCmd.ExecuteReader()

            Do While myReader.Read()
                'myReader.GetValue(1).ToString''
                cmbStorename.Items.Add(myReader.GetValue(3).ToString)
                cmbstore.Items.Add(myReader.GetValue(5).ToString)
            Loop
            cmbStorename.Text = "Choose a Store"
            myReader.Close()
            myConn.Close()
            append("Initializing Stores..")
            ToolStripStatusLabel1.Text = "Idle"
        Catch ex As Exception

        End Try
    End Sub
#End Region
#Region "Misc"
    Sub append(Msg As String)
        'txtLogs.AppendText(Now.ToString & " : " & Msg & vbCrLf)
        txtLogs.Text = Now.ToString & " : " & Msg & vbCrLf & txtLogs.Text
    End Sub
    Sub ResetControl()
        txtguestname.Text = ""
        txtaddress.Text = ""
        txtcontactno.Text = ""
        txtorder.Text = ""
        txttotalbill.Text = ""
        txtspecialins.Text = ""
        txtchangefor.Text = ""
    End Sub
    Sub WhileRunning(en As Boolean)
        Try
            For Each cont As Control In GroupBox1.Controls
                cont.Enabled = en
            Next
            Button1.Enabled = en
        Catch ex As Exception

        End Try
        

    End Sub
#End Region


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        'sender = My.Computer.Name
        'If txttotalbill.Text > txtchangefor.Text Then
        'MsgBox("Insufficient Tender Amount!", MsgBoxStyle.Critical)
        'Return
        'End If
        If cmbStorename.Text = "" Then
            MsgBox("Invalid Store!", vbCritical)
            Return
        End If
        If txtguestname.Text = "" Then
            MsgBox("Invalid Guestname!", vbCritical)
            Return
        End If
        If txtaddress.Text = "" Then
            MsgBox("Invalid Address!", vbCritical)
            Return
        End If
        If txtorder.Text = "" Then
            MsgBox("Invalid Order!", MsgBoxStyle.Critical)
            Return
        End If
        If IsNumeric(txttotalbill.Text) = False Then
            MsgBox("Invalid Bill!", MsgBoxStyle.Critical)
            Return
        End If
        If IsNumeric(txtchangefor.Text) = False Then
            MsgBox("Change For!", MsgBoxStyle.Critical)
            Return
        End If
        If txttotalbill.Text = "" Then
            MsgBox("Invalid Bill!", MsgBoxStyle.Critical)
            Return
        End If
        If txtchangefor.Text = "" Then
            MsgBox("Change For!", MsgBoxStyle.Critical)
            Return
        End If
        Dim t As New Threading.Thread(AddressOf SendDeliverySQL)
        t.Start()
    End Sub

    Private Sub RefreshOrdersToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles RefreshOrdersToolStripMenuItem.Click
        Dim t As New Threading.Thread(AddressOf GetMySentData)
        t.Start()
    End Sub

    Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        e.Cancel = True
        WindowState = FormWindowState.Minimized
        MainForm.NotifyIcon1.Visible = True
        MainForm.NotifyIcon1.BalloonTipIcon = ToolTipIcon.Info
        MainForm.NotifyIcon1.BalloonTipTitle = "SDM Server"
        MainForm.NotifyIcon1.BalloonTipText = "Relay Delivery Still Running"
        MainForm.NotifyIcon1.ShowBalloonTip(5000)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        My.Settings.Reload()
        'Resize
        MainForm.AccountType = 1
        Timer1.Interval = MainForm.TimerDelay * 1000
        CheckForIllegalCrossThreadCalls = False
        GetStores()
        Dim t As New Threading.Thread(AddressOf GetMySentData)
        t.Start()
    End Sub

    Private Sub cmbStorename_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbStorename.SelectedIndexChanged
        Try
            cmbstore.SelectedIndex = cmbStorename.SelectedIndex
        Catch ex As Exception

        End Try


    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        Dim t As New Threading.Thread(AddressOf GetMySentData)
        t.Start()

    End Sub

    Private Sub ReportingToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ReportingToolStripMenuItem.Click
        Dim datepck As New datepick
        datepck.ReportType = "PerTransaction"
        datepck.ShowDialog()
    End Sub
End Class
